﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Gnosis.Babel;
using Gnosis.SQLite.Clauses;

namespace Gnosis.SQLite
{
    public class TableName
        : Expression, ITableName
    {
        public TableName(string name)
            : base(name)
        {
            _name = name;
        }

        public TableName(ISelect select, string alias)
            : base(string.Format("{0} AS{ 1}", select, alias))
        {
            _name = select.ToString();
            _alias = alias;
        }

        public TableName(string name, string alias)
            : base(string.Format("{0} AS {1}", name, alias))
        {
            _name = name;
            _alias = alias;
        }

        private readonly string _name;
        private readonly string _alias;

        protected string GetColumnName(string column)
        {
            return (_alias != null) ? string.Format("{0}.{1}", _alias, column) : column;
        }

        #region ITableName Members

        public ISource InnerJoin(ISource table, IPredicate expression)
        {
            return new JoinSource(this, JoinOperator.Inner, table, new JoinConstraint(new On(expression)));
        }

        public ISource LeftOuterJoin(ISource table, IPredicate expression)
        {
            return new JoinSource(this, JoinOperator.LeftOuter, table, new JoinConstraint(new On(expression)));
        }

        #endregion

        #region ISource

        public IInteger LastInsertedId
        {
            get
            {
                return new LastInsertRowId();
            }
        }

        #endregion
    }
}
